package com.wmapp.language;

import java.io.IOException;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wmapp.utils.SimpleStringUtils;
/**
 * This bean is session scope.
 * @author dengl
 *
 */
public class LangImpl implements Lang {
	private static Log log = LogFactory.getLog(LangImpl.class);
	
	private final String BASE_NAME="messages_";
	
	private Properties properties=new Properties();
	
	// --------------- constructor -----------------------
	public LangImpl() {
		loadProperties(EN);
	}
	
	@Override
	public String getMsg(String key){
		String ret=null;
		ret=properties.getProperty(key);
		return ret;
	}
	
	@Override
	public String getMsg(String key,String[] params){
		String ret=null;
		ret=getMsg(key);
		
		if(ret!=null&&params!=null){
			for (int i = 0; i < params.length; i++) {
				ret=ret.replaceFirst(SimpleStringUtils.join("\\{",String.valueOf(i),"\\}"),params[i]);
			}
		}
		
		return ret;
	}
	
	@Override
	public void setLocale(String locale) {
		if(isLegalLocale(locale)){
			loadProperties(locale);
		}
	}
	
	private void loadProperties(String locale){
		if(isLegalLocale(locale)){
			String fileName=SimpleStringUtils.join(BASE_NAME,locale,".properties");
			try {
				properties.load(LangImpl.class.getResourceAsStream(SimpleStringUtils.join("/",fileName)));
			} catch (IOException e) {
				log.error(SimpleStringUtils.join("load resource ",fileName," fail."), e);
			}
		}
	}
	
	private boolean isLegalLocale(String locale){
		boolean ret=false;
		
		for (int i = 0; i < LANGS.length; i++) {
			if(locale!=null&&locale.equals(LANGS[i])){
				ret=true;
				break;
			}
		}
		
		return ret;
	}
}
